package com.example.myapplication.slice.slice;

import baidu.AdvancedGeneral;
import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.net.NetHandle;
import ohos.rpc.MessageParcel;

import java.io.ObjectOutputStream;
import java.nio.charset.CoderMalfunctionError;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

public class voiceLookupPageAbilitySlice extends AbilitySlice implements Component.ClickedListener {



    //获取权限
    private void requestPermission() {
        String[] permission = {
                "ohos.permission.MICROPHONE",
        };
        List<String> applyPermissions = new ArrayList<>();
        for (String element : permission) {
            if (verifySelfPermission(element) != 0) {
                if (canRequestPermission(element)) {
                    applyPermissions.add(element);
                }
            }
        }
        requestPermissionsFromUser(applyPermissions.toArray(new String[0]), 0);
    }




    Button start;
    Button stop;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_voiceLookup_ability_main1);
        //获取权限
        requestPermission();

        start = (Button)findComponentById(ResourceTable.Id_start);

        start.setClickedListener(this);

        stop = (Button)findComponentById(ResourceTable.Id_stop);

        stop.setClickedListener(this);

        String abilityName = "someAbility"; // 确保这个值不是null
        int command = 123; // 确保这个值不是null，因为int类型不能是null，但必须是有效的整数
        Map<String, Object> params = new HashMap<>();


        if (start != null) {
            // 设置按钮点击事件监听器
            start.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    voiceLookupPageAbilitySlice.callAbility(abilityName,command,params);
                }
            });
        }else if(stop != null){
            voiceLookupPageAbilitySlice.subAbility(abilityName,command,null);
        }
    }


    private static final Map<String, Consumer<Map<String, Object>>> subscribers = new ConcurrentHashMap<>();

    // 调用服务能力的方法
    public static CompletableFuture<Map<String, Object>> callAbility(String abilityName, int command, Map<String, Object> params) {
        // 这里只是模拟异步操作，实际情况下可能涉及网络通信或其他复杂逻辑
        CompletableFuture<Map<String, Object>> future = CompletableFuture.supplyAsync(() -> {
            // 执行实际的服务能力逻辑
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "ServiceAbility called successfully.");
            // 根据abilityName和command执行不同的逻辑
            return result;
        });
        return future;
    }

    public CompletableFuture<Map<String, Object>> unSubAbility(String abilityName, int command) {
        // 取消订阅逻辑

        start = (Button)findComponentById(ResourceTable.Id_start);

        start.setClickedListener(this);



        CompletableFuture<Map<String, Object>> future = CompletableFuture.supplyAsync(() -> {


            String key = abilityName + "_" + command;
            boolean isUnsubscribed = subscribers.remove(key) != null; // 注意这里检查移除操作是否成功
            Map<String, Object> result = new HashMap<>();
            if (isUnsubscribed && stop != null) {
                result.put("code", 200);
                result.put("message", "Unsubscribed successfully.");
            } else {
                result.put("code", 404);
                result.put("message", "No subscription found.");
            }
            return result; // 返回结果Map
        });
        return future;
    }


        // 订阅Java端结果事件的方法
    public static CompletableFuture<Map<String, Object>> subAbility(String abilityName, int command, Consumer<Map<String, Object>> callback) {
        // 订阅逻辑
        CompletableFuture<Map<String, Object>> future = CompletableFuture.supplyAsync(() -> {
            String key = abilityName + "_" + command;
            if (!subscribers.containsKey(key)) {
                subscribers.put(key, callback);
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "Subscribed successfully.");
                return result;
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 409); // 冲突，例如已经订阅了
                result.put("message", "Already subscribed.");
                return result;
            }
        });

        Map<String, Object> message = new HashMap<>();
        sendMessageToSubscribers(abilityName, command, message);

        return future;
    }

    // 发送消息给订阅者的模拟方法（实际实现可能涉及网络通信）
    private static void sendMessageToSubscribers(String abilityName, int command, Map<String, Object> message) {
        String key = abilityName + "_" + command;
        subscribers.getOrDefault(key, (data) -> {}).accept(message);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {

    }
}
